// ------------------------------------------------------------------------------------------------------------------------
// Plemiona.pl 5.X Skrypt użytkowy
//
// Nazwa:      Scout Report Evaluator
// Wersja:     2.0 PL UNIVERSAL PSP
// Autor:      Debren (Forum Plemion)
// Dostosował: Lukasz032 (Plemiona Ś7)
//
// Tagi specjakne:
// Licencja:   Creative Commons Uznanie autorstwa - Brak komercyjnego zastosowania - Na tych samych warunkach 2.0 Polska
// Informacje: http://creativecommons.org/licenses/by-nc-sa/2.0/pl/legalcode
// Support:    lvwnbrz@lykamspam.pl
//
// ------------------------------------------------------------------------------------------------------------------------

function ScoutREstart(unitPrep,worldSpeed) { 
 
 switch (unitPrep) {
   case "p":
    var farmingUnit = "Piki";
    break;
   case "t":
    var farmingUnit = "Topki";
    break;
   default:
    var farmingUnit = "Piki";
 }
 
 var timeDifference=0;
 var unitSpeed=1;
 var maxToHaul=15000;
 
 if ((typeof worldSpeed) == "undefined") {
   worldSpeed = "1";
 };
 
 var units=new Array();
 units['Lekka']=new Array(600,80,'light');
 units['Topki']=new Array(1080,10,'axe');
 units['Ciezka']=new Array(660,50,'heavy');
 units['LNK']=new Array(660,50,'marcher');
 units['Piki']=new Array(1080,25,'spear');
 units['Rycek']=new Array(600,100,'knight');
 unitOfChoice=units[farmingUnit];
 var warehouseMax=new Array(0,1000,1229,1512,1859,2285,2810,3454,4247,5222,6420,7893,9705,11932,14670,18037,22177,27266,33523,41217,50675,62305,76604,94184,115798,142373,175047,215219,264611,325337,400000);
 var productionPerHour=new Array(0,30,35,41,47,55,64,74,86,100,117,136,158,184,214,249,289,337,391,455,530,616,717,833,959,1127,1311,1525,1774,2063,2400);
 var hidingPlace=new Array(0,150,200,267,356,474,632,843,1125,1500,2000);

 function createCookie(name,value,days) {

    if (days)
    {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
 }
 
 function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++)
    {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
 }
 
 function getCoordinates(theString)
 {
    theString=theString.split("|");
    var x=theString[theString.length-2];
    var y=theString[theString.length-1];

    x=x.split("(");
    x=x[x.length-1];
    y=y.split(")");
    y=y[0];
    var coordinates=new Array(x,y);
    return coordinates;
 }
 
 function getLevel(building)
 {
    var tRow=document.getElementsByTagName('tr');
    for(i=0;i<tRow.length;i++)
    {
        var thead=tRow[i].getElementsByTagName('th')[0];
        if(thead)
        {
            if(thead.firstChild.nodeValue==='Budynki:')
            {

                var text=tRow[i].getElementsByTagName('td')[0];
                text=text.innerHTML;
                text=text.split("<BR>");
                for(j=0;j<text.length;j++)
                {
                    var line=text[j];
                    if(line.search(building)!= -1)
                    {

                        var level=line.split(")");

                        level=level[0].split(" ");
                        level=level[level.length-1];
                        return level;
                        break;

                    }

                }
                return 0;
            }
        }
    }

 }

 function checkOverflow(amount,warehouse, hiding)
 {
    var amount=parseInt(amount);

    var max=warehouseMax[warehouse]-hidingPlace[hiding];

    if(amount>max)
    {
        return max;
    }
    else
    {
        return amount;
    }
 }
 
 function getDurationInSeconds(originX, originY, targetX, targetY, speed, unitSpeed, unit)
 {
    var x=originX-targetX;
    var y=originY-targetY;
    var fields=Math.sqrt((x*x)+(y*y));
    var overallSpeed=speed*unitSpeed;
    var secondsPerField=unit/overallSpeed;

    var duration=Math.round(secondsPerField*fields);
    return duration;
 }
 
 function getInnerHTMLString(tableHeader)
 {
    var tbls=document.getElementsByTagName('table');
    for(var i=0;i<tbls.length;i++)
    {
        var thead=tbls[i].getElementsByTagName('th')[0];
        if(thead)
        {
            if(thead.firstChild.nodeValue===tableHeader)
            {
                var village=tbls[i];
                var row=village.getElementsByTagName('tr')[1];
                var cell=row.getElementsByTagName('td')[1];
                cell=cell.innerHTML;
                return cell;
            }
        }
    }
 }
 
 
 function elapsedTime(dateString, timeDifference)
 {

    var dThen=Date.parse(dateString);
    dThen=dThen+3155760000000;

    var dNow=new Date();
    dNow=dNow.getTime();
    dNow=dNow-((timeDifference*3600)*1000);

    var minutes=((dNow-dThen)/1000)/60;

    return minutes;
 }
 
 
 function timeOfReport()
 {
    var tRow=document.getElementsByTagName('tr');
    for(i=0;i<tRow.length;i++)
    {
        var tCell=tRow[i].getElementsByTagName('td');
        if(tCell[0])
        {
            if(tCell[0].innerHTML==="Wysłane")
            {
                sentTime=tCell[1].innerHTML;
                return sentTime;
            }
        }

    }
 }
 
 function sameVillage()
 {
    var anchors=document.getElementsByTagName('a');
    for(i=0;i<anchors.length;i++)
    {
        if(anchors[i].firstChild.nodeValue==='Wprowadź wojska do symulatora')
        {
            var theLink=anchors[i].getAttribute('href');
            theLink=theLink.split("&");
            return theLink[0];
        }
    }
 }

 function originalVillage()
 {
    var tbls=document.getElementsByTagName('table');
    for(var i=0;i<tbls.length;i++)
    {
        var thead=tbls[i].getElementsByTagName('th')[0];
        if(thead)
        {
            if(thead.firstChild.nodeValue==='Agresor:')
            {
                var defVill=tbls[i];
                var anchor=defVill.getElementsByTagName('a');
                anchor=anchor[anchor.length-1];
                var link=anchor.getAttribute('href');
                link=link.split("=");
                link=link[link.length-1];
                return "/game.php?village="+link;
            }
        }
    }
 }


 function targety()
 {
    var tbls=document.getElementsByTagName('table');
    for(var i=0;i<tbls.length;i++)
    {
        var thead=tbls[i].getElementsByTagName('th')[0];
        if(thead)
        {
            if(thead.firstChild.nodeValue==='Obrońca:')
            {
                var defVill=tbls[i];
                var anchor=defVill.getElementsByTagName('a');
                anchor=anchor[anchor.length-1];
                var link=anchor.getAttribute('href');
                link=link.split("=");
                link=link[link.length-1];
                return link;
            }
        }
    }
 }

 function removeHTMLTags(strInputCode){return strInputCode.replace(/<\/?[^>]+(>|$)/g,"");}


 function production(mine)
 {
    if(mine===0)
    {
    return 5/60;
    }
    else
    {
        return productionPerHour[mine]/60;
    }
 }

 function scoutReportClick()
 {

    var target=getCoordinates(getInnerHTMLString("Obrońca:"));
    var targetX=target[0];
    var targetY=target[1];

    var warehouse=getLevel(/Spichlerz/i);
    var hidingPlace=getLevel(/Schowek/i);


    var timberCamp=getLevel(/Tartak/i);
    var woodPerMin=(production(timberCamp)*worldSpeed);
    var clayPit=getLevel(/Cegielnia/i);
    var clayPerMin=(production(clayPit)*worldSpeed);
    var ironMine=getLevel(/Huta żelaza/i);
    var ironPerMin=(production(ironMine)*worldSpeed);

    var elapsedTimeInMins=Math.ceil(elapsedTime(timeOfReport(), timeDifference));

    var trow=document.getElementsByTagName('tr');
    for(var i=0;i<trow.length;i++)
    {
        var thead=trow[i].getElementsByTagName('th')[0];
        if(thead)
        {
            if(thead.firstChild.nodeValue==='Wyszpiegowane surowce:')
            {
                var tcell=trow[i].getElementsByTagName('td')[0];
                var finText=removeHTMLTags(tcell.innerHTML);
                finText=finText.replace(/\./gi,"");
                finText=finText.split(" ");
                var wood=parseInt(finText[0]);
                var clay=parseInt(finText[1]);
                var iron=parseInt(finText[2]);
                var cookieValue=elapsedTimeInMins+"|"+wood+"|"+clay+"|"+iron+"|"+warehouse+"|"+hidingPlace+"|"+woodPerMin+"|"+clayPerMin+"|"+ironPerMin+"|"+targetX+"|"+targetY;



                    createCookie("booreporter", cookieValue, 1);
                    var targ=targety();
                    var link=originalVillage();
                    var url=link+"&screen=place&mode=command&target="+targ;
                    window.open(url,'newwindow', config='height=650,width=950, toolbar=no, menubar=no, scrollbars=no, resizable=yes,location=no,directories=no, status=no');

            }
        }
    }
 
 }

 function getRallyPointCoords()
 {
    var titleString=document.getElementsByTagName('title')[0];
    titleString=titleString.innerHTML;
    titleString=titleString.split(")");
    titleString=titleString[titleString.length-2];
    titleString=titleString.split("(");
    titleString=titleString[titleString.length-1];
    var origin=titleString.split("|");
    return origin;
 }
 
 function checkTarget(targetX, targetY)
 {
    var inputs=document.getElementsByTagName('input');
    for(i=0;i<inputs.length;i++)
    {
        var name=inputs[i].getAttribute('name');
        if(name==='x')
        {
            var x=inputs[i].value;
        }
        if(name==='y')
        {
            var y=inputs[i].value;
        }
    }
    if((parseInt(targetX)==x) && (parseInt(targetY)==y))
    {return 1;}
    else{return -1;}
 }

 function fillUnits(resources,units,numberOfScouts)
 {
    if(resources>maxToHaul)
    {
        var amount=Math.ceil(maxToHaul/units[1]);
    }
    else
    {
        var amount=Math.ceil(resources/units[1]);
    }
    var fields=document.getElementsByTagName('input');
    for(var i=0;i<fields.length;i++)
    {
        var thename=fields[i].getAttribute('name');
        if(thename)
        {
            if(thename==='spy')
            {
                var next = fields[i].nextSibling;
                next = next.nextSibling;
                s = next.firstChild.nodeValue;
                s=s.split("(");
                s=s[s.length-1];
                scouts=s.replace(/[)]/g, "");
                scouts=parseInt(scouts);
                if(numberOfScouts>=scouts)
                {
                    alert("Brakuje zwiadowców!");
                }
                else
                {
                    document.forms[0].spy.value=numberOfScouts;
                }
            }
            if(thename===units[2])
            {
                var next = fields[i].nextSibling;
                next = next.nextSibling;
                s = next.firstChild.nodeValue;
                s=s.split("(");
                s=s[s.length-1];
                s=s.replace(/[)]/g, "");
                var t=parseInt(s);
                if(t===0)
                {
                    return 1;
                }else if(t>amount)
                {
                    document.forms[0][units[2]].value=amount;
                }
                else
                {
                    document.forms[0][units[2]].value=t;
                }
            }
        }
    }
    return 0;
 }
 
 function rallyPointClick()
 {
     var cookieValue=readCookie("booreporter");
     cookieValue=cookieValue.split("|");
 
     var elapsedTimeInMins=parseInt(cookieValue[0]);
     var wood=parseInt(cookieValue[1]);
     var clay=parseInt(cookieValue[2]);
     var iron=parseInt(cookieValue[3]);
     var warehouse=parseInt(cookieValue[4]);
     var hidingP=parseInt(cookieValue[5]);
     var woodPerMin=parseFloat(cookieValue[6]);
     var clayPerMin=parseFloat(cookieValue[7]);
     var ironPerMin=parseFloat(cookieValue[8]);
     var targetX=parseInt(cookieValue[9]);
     var targetY=parseInt(cookieValue[10]);
 
     var check=checkTarget(targetX, targetY);
     if(check==-1)
     {alert("Zmieniono cel od ostatniego użycia skryptu. Obliczenie ilości jednostek niemożliwe.");}
 
     var origin=getRallyPointCoords();
     var originX=origin[0];
     var originY=origin[1];
 
     var durationInMinutes=(Math.ceil(getDurationInSeconds(originX, originY, targetX, targetY, worldSpeed, unitSpeed, unitOfChoice[0])/60));
     var totalTimeInMinutes=elapsedTimeInMins+parseInt(durationInMinutes);
     var excessWood=parseInt(Math.floor(totalTimeInMinutes*woodPerMin));
     var excessClay=parseInt(Math.floor(totalTimeInMinutes*clayPerMin));
     var excessIron=parseInt(Math.floor(totalTimeInMinutes*ironPerMin));
 
     wood=parseInt(wood)+parseInt(excessWood);
     wood=checkOverflow(wood, warehouse, hidingP);
     clay=clay+excessClay;
     clay=checkOverflow(clay, warehouse, hidingP);
     iron=iron+excessIron;
     iron=checkOverflow(iron, warehouse, hidingP);
     var resources=wood+clay+iron;
     var i=fillUnits(resources,unitOfChoice,1);
 }
 
 function main() {
     var url=document.URL;
     if(url.search(/screen=report/)!= -1)
     {
         scoutReportClick();
     }
     else if(url.search(/screen=place/)!= -1)
     {
         rallyPointClick();
     }
 }
 
 main();
 
}
